package cz.najman.emdroid.ui;

import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.markupartist.android.widget.ActionBar;

import cz.najman.emdroid.R;
import cz.najman.emdroid.helper.EventHelper;
import cz.najman.emdroid.helper.EventInstitutionManagerHelper;
import cz.najman.emdroid.helper.RegistrationStateHelper;
import cz.najman.emdroid.helper.UserHelper;
import cz.najman.emdroid.listener.ActionBarOnDataUpdatedListener;
import cz.najman.emdroid.listener.OnDataUpdatedListener;
import cz.najman.emdroid.mappings.Event;
import cz.najman.emdroid.mappings.EventInstitutionManager;
import cz.najman.emdroid.mappings.User;

/**
 * @author  Lukáš Najman
 */
public class AvailableEventsActivity extends ActionBarActivity {
	private static final String TAG = "activity";
	
	private Context mContext;	
	private EMDroidApplication mApplication;
	
	private EventHelper mEventHelper;
	private EventInstitutionManagerHelper mEventInstitutionManagerHelper;
	private UserHelper mUserHelper;
	private RegistrationStateHelper mRegistrationStateHelper;
	
	private ListView mList;
	private SimpleCursorAdapter mAdapter;
	private Cursor mCursor;

	private OnDataUpdatedListener mCustomListener;	
	
	private int mUserId;
	private int mAction;
	private int mInstitutionId;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Setup the GUI */
		setContentView(R.layout.activity_list_with_actionbar);
		mList = (ListView) findViewById(R.id.lvList);
		setActionBarTitle(R.string.app_name);
		setActionBarHomeAction( new Intent(this, HomeActivity.class) );
		
		/* Get needed references */
		mApplication = (EMDroidApplication) getApplication();
		mEventHelper = mApplication.getEventHelper();	
		mEventInstitutionManagerHelper = mApplication.getEventInstitutionManagerHelper();
		mUserHelper = mApplication.getUserHelper();
		mRegistrationStateHelper = mApplication.getRegistrationStateHelper();

		/* Initialize activity variables */
		mContext = this;		
		mCustomListener = new AvailableAventsOnDataUpdatedListener(mActionBar);
	}
	
	@Override
	protected void onStart() {
		
		Intent startIntent = getIntent();
		mUserId = startIntent.getIntExtra("userId", -1);
		mAction = startIntent.getIntExtra("action", -1);
		super.onStart();
		
		
	}

	@Override
	protected void onResume() {		
		mEventHelper.registerListener(Event.class.getCanonicalName(), mCustomListener);			
		mEventInstitutionManagerHelper.registerListener(EventInstitutionManager.class.getCanonicalName(), mCustomListener);
		if(mUserId != -1){
			mRegistrationStateHelper.retrieveUsersRegistartionStates(mUserId);
			mEventHelper.retrieveUsersAvailableEvents(mUserId);			
		
			Cursor user = mUserHelper.getUserById(mUserId, new String[] {User.INSTITUTION_ID});
			if(user.moveToFirst()){
				int institutionIndex = user.getColumnIndex(User.INSTITUTION_ID);
				mInstitutionId = user.getInt(institutionIndex);
				mEventInstitutionManagerHelper.retrieveInstitutionsEventInstitutionManagers(mInstitutionId);
				setupList(mInstitutionId);				
			}
		}
		
		super.onResume();	}

	@Override
	protected void onPause() {
		mEventHelper.unregisterListener(Event.class.getCanonicalName());
		mEventInstitutionManagerHelper.unregisterListener(EventInstitutionManager.class.getCanonicalName());
		super.onPause();
	}
	
	private void setupList(int institutionId){		
		mCursor = mEventHelper.getUsersAvailableEvents(institutionId, null, null, null);
		startManagingCursor(mCursor);		
		mAdapter = new SimpleCursorAdapter(AvailableEventsActivity.this,
				R.layout.list_item_event, mCursor,
				new String[] { Event.EVENT_NAME, Event._ID },
				new int[] { R.id.tvEventName, R.id.tvEventId });		
		mList.setAdapter(mAdapter);		
		mList.setOnItemClickListener(listViewOnItemClickListener);
	}
	
	
	public class AvailableAventsOnDataUpdatedListener extends ActionBarOnDataUpdatedListener {

		public AvailableAventsOnDataUpdatedListener(ActionBar actionBar) {
			super(actionBar);
		}
		
		@Override
		protected void onFinished(Class objectClass) {	
			if(mCursor != null){
				mCursor.requery();
			}						
			super.onFinished(objectClass);
		}	
		
	}
	
	final OnItemClickListener listViewOnItemClickListener = new OnItemClickListener() {
		
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
			LinearLayout view = (LinearLayout) v;
			TextView tv = (TextView) view.getChildAt(view.getChildCount()-1);
			int eventId = Integer.valueOf(tv.getText().toString());
			
			Intent intent = new Intent(mContext, EventDetailsActivity.class);
			intent.putExtra(EventDetailsActivity.EVENT_ID, eventId);
			intent.putExtra(EventDetailsActivity.USER_ID, mUserId);
			intent.putExtra(EventDetailsActivity.ACTION_TYPE, EventDetailsActivity.SHOW_EVENT_TO_REGISTER);
			
			startActivity(intent);			
		}
	};
	
}